package com.amap.gunfighting;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.amap.mapapi.core.GeoPoint;
import com.amap.mapapi.map.MapActivity;
import com.amap.mapapi.map.MapController;
import com.amap.mapapi.map.MapView;
import com.amap.mapapi.map.MyLocationOverlay;

public class Map extends MapActivity
{
	private MapView mMapView;
	private MapController mMapController;
	private GeoPoint point;
	
	static double Lon = 0;
    static double Lat = 0;
    
    String strUrl = "http://83.251.86.183:8080/ZRTrafficWeb/trafficweb";
    //String strUrl = "http://213.103.200.57:8080/zr/trafficweb";
    URL url = null;
	static String username ="";
	String password ="";
	
	private LocationManager mlocManager;
	private LocationListener mlocListener = new MyLocationListener();
	
	
	public void onDestroy()
	{
		super.onDestroy();
	}
	public void onPause()
	{
		super.onPause();
	}
	public void onResume()
	{
		super.onResume();
	}

	
	
	@Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map);
        
        mMapView = (MapView) findViewById(R.id.mapView);
		mMapView.setBuiltInZoomControls(true);
		mMapController = mMapView.getController();
		//point = new GeoPoint((int) (59.351756 * 1E6), (int) (18.057822 * 1E6));
		point = new GeoPoint((int) (39.9012006 * 1E6), (int) (116.295196 * 1E6));
		mMapController.setCenter(point);
		mMapController.setZoom(13);
		
		// get username and password from Login.java
        username = Login.userName.getText().toString();
    	password = Login.passWord.getText().toString();
    	
		/* Use the LocationManager class to obtain GPS locations */
		mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5*1000, 10, mlocListener);

		MyLocationOverlay mLocationOverlay = new MyLocationOverlay(this, mMapView);
		// to show your current location on the map, it is ONLY efficient in area of China
		mLocationOverlay.enableMyLocation();
		// to show the compass on the map
		mLocationOverlay.enableCompass();
		mMapView.getOverlays().add(mLocationOverlay);
		
		Button next = (Button) findViewById(R.id.bFire);
		next.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				//Intent myIntent = new Intent(view.getContext(), Fire.class);
				//startActivityForResult(myIntent, 0);
				
				startActivity(new Intent(Map.this, Fire.class));
				 //finish the login activity
				 Map.this.finish();
			}
		});
		
		/*
		 * Whenever your current position is changed, positions of your enemies will be refreshed as well.
		 *In the further step, refresh produces should be processed at every t constant of time.  
		 * */
		Drawable marker = getResources().getDrawable(R.drawable.da_marker_red);
		marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight());
		mMapView.getOverlays().add(new com.amap.gunfighting.OverItemT(marker, getApplicationContext())); 
    }
	
	// MyLocationListner
	class MyLocationListener implements LocationListener
	{
		public void onLocationChanged(Location loc) 
		{
			// TODO Auto-generated method stub	
			Lon = loc.getLongitude();
			Lat = loc.getLatitude();
			point = new GeoPoint((int)(Lat*1e6), (int)(Lon*1e6));
			mMapController.animateTo(point);
			
	        //send updated latitude and longitude to the server
			try 
			{				
				url = new URL(strUrl);
				HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
				
				urlConn.setDoInput(true);
				urlConn.setDoOutput(true);
				urlConn.setRequestMethod("POST");
				urlConn.setUseCaches(false);
				urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
				urlConn.setRequestProperty("Charest", "utf-8");
				// to connect to the server side
				urlConn.connect();
				
				DataOutputStream dop = new DataOutputStream(urlConn.getOutputStream());
				dop.writeBytes("point=" + URLEncoder.encode("location","utf-8"));
				//it is essential that to add "&" to separate two strings
				dop.writeBytes("&username=" + URLEncoder.encode(username,"utf-8"));
    			dop.writeBytes("&password=" + URLEncoder.encode(password,"utf-8"));
				dop.writeBytes("&lon=" + URLEncoder.encode(Double.toString(Lon),"utf-8"));
				dop.writeBytes("&lat=" + URLEncoder.encode(Double.toString(Lat),"utf-8"));
				dop.flush();
				dop.close();
				
				DataInputStream dis = new DataInputStream(urlConn.getInputStream());
				String locPassage = dis.readUTF();
				// to disconnect the server side
				urlConn.disconnect();
				if("Succeed".equalsIgnoreCase(locPassage))
				{
					//nothing
				}
			}
			catch (MalformedURLException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
			catch (IOException e)
			{
				e.printStackTrace();
			}//end of sending updated latitude and logititude
		}


		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub

			
		}


		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
			
		}


		public void onStatusChanged(String provider, int status,
				Bundle extras) {
			// TODO Auto-generated method stub
			
		}
	}//end of MyLocationListner
}
